package com.yxjx.duoxue.versionupdate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.yxjx.duoxue.R;
import com.yxjx.duoxue.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdateManager {
	
	private static final int DOWNLOAD_PROGRESS = 1;
	private static final int DOWNLOAD_DONE = 2;
	
	private static final String ROOT_DIR = "yxjx_cache";
	
	private Context mContext;
	private Dialog mNoticeDialog;
	private Dialog mDownloadDialog;
	
	private ProgressBar mProgressBar;
	private TextView mDetailText;
	private TextView mPctText;
	private String mApkUrl = "";
	protected int mProgress = 0;
	
	private boolean mIntereptFlag = false;
	
	private String mUpdateMsg;
	private static final String saveFileName = "duoxue.apk";
	File mCache;
	// M unit.
	private float mTotalSize = 0;
	private float mDownloadedSize = 0;

	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case DOWNLOAD_PROGRESS:
				mProgressBar.setProgress(mProgress);
				mDetailText.setText(String.format("%.2f", mDownloadedSize) + 
						mContext.getResources().getString(R.string.down_prefix)
						+ String.format("%.2f", mTotalSize) + mContext.getResources().getString(R.string.down_post));
				mPctText.setText((int) (mDownloadedSize * 100 / (mTotalSize + 0.00001)) + 
						mContext.getResources().getString(R.string.finish_end));
				
				
				break;
			case DOWNLOAD_DONE:
				mDownloadDialog.dismiss();
				installApk();
				break;

			default:
				break;
			}
		}
	};


	private UpdateManager (Context context) {
        mCache = new File(Environment.getExternalStorageDirectory(), ROOT_DIR);
		mContext = context;
		mUpdateMsg = mContext.getResources().getString(R.string.download_me_now);
	}
	
	public UpdateManager(Context mContext2, String downloadUril) {
		mCache = new File(Environment.getExternalStorageDirectory(), ROOT_DIR);
		mContext = mContext2;
		mApkUrl = downloadUril;
	}

	// Test
	// http://file.learnmore.com.cn/files/DuoXue-offical.apk
	public void test() {
		new UpdateManager(mContext).showDownloadDialog(); // direct download
		new UpdateManager(mContext).showNoticeDialog(); // indirectly download
	}
	
	private String getAppVersionName() {
		return "[TODO] new version";
	}
	
	public void showNoticeDialog() {
		AlertDialog.Builder builder = new Builder(mContext);
		
		builder.setTitle(mContext.getResources().getString(R.string.has_checked_new_vers) + getAppVersionName());
		builder.setMessage(mUpdateMsg);
		builder.setPositiveButton(R.string.update_now, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				showDownloadDialog();
			}
		});
		builder.setNegativeButton(R.string.remind_later, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		mNoticeDialog = builder.create();
		mNoticeDialog.show();
	}
	
	public void showDownloadDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setTitle(R.string.downloading);
		
		View view = LayoutInflater.from(mContext).inflate(R.layout.segment_download_progress, null);
		mProgressBar = (ProgressBar) view.findViewById(R.id.progress);
		mDetailText = (TextView) view.findViewById(R.id.detail);
		mPctText = (TextView) view.findViewById(R.id.percent);

		builder.setView(view);
		builder.setNegativeButton(R.string.cancel1, new OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				mIntereptFlag = true;
			}
		});
		builder.setCancelable(false);
		
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		
		downloadApk();
		
 	}
	
	private void downloadApk() {
	    new Thread(mDownloadApkRunnable).start();
    }

	private Runnable mDownloadApkRunnable = new Runnable() {
		
		@Override
	    public void run() {
			try {
	            URL url = new URL(mApkUrl);
	            
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.connect();
	            int length = connection.getContentLength();
	            mTotalSize = (length /  1024.f / 1024.f);
	            InputStream is = connection.getInputStream();
	            
	            File file = new File(Environment.getExternalStorageDirectory(), ROOT_DIR);
	            if (!file.exists()) {
	            	file.mkdir();
	            }
	            File apkFile = new File(mCache, saveFileName);
	            FileOutputStream fos = new FileOutputStream(apkFile);
	            
	            int count = 0;
	            byte buf[] = new byte[1024];
	            
	            do {
	            	int numread = is.read(buf);
	            	count += numread;
	            	mDownloadedSize = count / 1024.f / 1024.f;
	            	
	            	// update progress
	            	mProgress = (int)(((float)count / length) * 100);
	            	mHandler.sendEmptyMessage(DOWNLOAD_PROGRESS);
	            	if (numread <=0) {
	            		mHandler.sendEmptyMessage(DOWNLOAD_DONE);
	            		break;
	            	}
	            	fos.write(buf, 0, numread);
	            } while (!mIntereptFlag);
	            fos.close();
	            is.close();
	            
            } catch (Exception e) {
	            Utils.logd("load apk file fail" + e);
	            mDetailText.post(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(mContext, R.string.downloading_error, Toast.LENGTH_LONG).show();
					}
				});
            }
		    
	    }
    };
    
    private void installApk() {
    	File file = new File(mCache, saveFileName);
    	if (!file.exists()) {
    		return;
    	}
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive"); 
    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//
    	mContext.startActivity(intent);
    }
    
    // if current version is latest version, and the temp apk exist, then delete the file in SDCard.

}
